import {Component, ElementRef, Input, OnInit, Renderer2, ViewChild} from '@angular/core';
import {PageVoService} from '../../service/page-vo.service';
import {PageVo} from '../../entity/page-vo';
import {DocSearchService} from '../../service/doc-search.service';
import {DocIndexService} from '../../service/doc-index.service';
import {Menu} from '../../entity/menu';
import {UserService} from '../../service/user.service';
import {User} from '../../entity/user';
import {Site} from '../../entity/site';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
    @Input()
    set site(value: Site) {
        this._site = value;
        this.onSiteSet();
    }

    /**
     * 命中结果
     * @type {Array}
     */
    menus: Menu[] = [];

    private _site: Site;

    /**
     * 当前搜索结果对应的关键词
     */
    searchedKeyword: string;

    private _keyword = '';

    /**
     * 是否显示登录框
     * @type {boolean}
     */
    showLoginForm = false;

    /**
     * 菜单类型：index=文档索引 {docId}=某个文档的接口菜单 {docId}.{version}=某个文档的历史接口菜单
     */
    menuType: string;

    @ViewChild('searchResultContenter')
    searchResultContenter: ElementRef;

    private timer: any;

    user: User;

    constructor(public pageVoService: PageVoService,
                private renderer: Renderer2,
                private docSearchService: DocSearchService,
                private docIndexService: DocIndexService,
                private userService: UserService) {
    }

    ngOnInit() {
        this.userService.userObservable.subscribe((user: User) => {
            if (user && user.name) {
                this.showLoginForm = false;
                this.user = user;
            } else {
                this.user = null;
            }
        });
    }

    showSearchResultContent() {
        if (this.menus.length > 0 && this.renderer && this.searchResultContenter) {
            setTimeout(() => {
                this.renderer.removeClass(this.searchResultContenter.nativeElement, 'hide');
            });

        }
    }

    private search(keyword: string) {
        if (keyword.length === 0 && this.searchedKeyword) {
            this.menus = [];
            this.searchedKeyword = '';
            if (this.timer) {
                clearTimeout(this.timer);
            }
            return;
        }
        if (this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
            this.doSearch();
        }, 500);
        this._keyword = keyword;
    }

    private doSearch() {
        const pageVo: PageVo = this.pageVoService.getPageVo();
        this.menuType = pageVo.leftMenuId;
        if (pageVo.leftMenuId === 'index') {
            // 索引页
            this.indexSearch();
        } else {
            // 文档页
            this.docSearch();
        }
    }

    private indexSearch() {
        this.docIndexService.search(this._keyword).subscribe(menus => {
            this.menus = menus;
            this.searchedKeyword = this._keyword;
        });
    }

    private docSearch() {
        this.docSearchService.search(this._keyword).subscribe(menus => {
            this.menus = menus;
            this.searchedKeyword = this._keyword;
        });
    }

    getLoginUrl(): string {
        this.userService.setCurrentUrl(window.location.href);
        const returnUrl = 'http://' + window.location.host + '/api/oauth2/fdd_uc/callback';
        return '/api/oauth2/fdd_uc?returnUrl=' + encodeURI(returnUrl);
    }

    getLoginParams() {
        const returnUrl = 'http://' + window.location.host + '/api/oauth2/' + this._site.auths[0] + '/callback';
        return `authServiceCode=${this._site.auths[0]}&returnUrl=${encodeURI(returnUrl)}`;
    }

    private onSiteSet() {
        const user = this.userService.getUser();
        if (user != null || !this._site || !this._site.auths) {
            return;
        }
        if (this._site && this._site.auths.includes('pwd')) {
            // this.showLoginForm = true;
        } else {
            const location = window.location;
            window.location.href = `${location.protocol}//${location.host}/api/oauth2/${this._site.auths[0]}?${this.getLoginParams()}`;
        }
    }

    get keyword(): string {
        return this._keyword;
    }

    set keyword(value: string) {
        this._keyword = value;
        this.search(value);
    }
    get site(): Site {
        return this._site;
    }
}
